<template>
  <div v-if="user.role=='ADMIN'">
    <div class="search">
      <el-input placeholder="请输入部门名称查询" clearable style="width: 200px" v-model="name"></el-input>
      <el-input placeholder="请输入部门编号查询" clearable style="width: 200px;margin-left: 10px" v-model="code"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>
    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="success" plain @click="exportData">导出</el-button>
<!--      <el-button type="success" plain-->
<!--                 @click="syncDepartments"-->
<!--                 :loading="isSyncing"-->
<!--                 :disabled="isSyncing">同步部门-->
<!--      </el-button>-->
    </div>

    <div class="table">
      <el-table :data="tableData" default-expand-all row-key="id" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" :reserve-selection="true" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="部门ID" width="100"></el-table-column>
        <el-table-column prop="name" label="部门名称"></el-table-column>
        <el-table-column prop="parentName" label="父级部门名称">
          <template #default="{ row }">
            <span v-if="row.parentName">{{ row.parentName }}</span>
            <el-tag v-else>无父级部门</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pid" label="父级ID">
          <template #default="{ row }">
            <span v-if="row.pid">{{ row.pid }}</span>
            <el-tag v-else>无</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="层级"></el-table-column>
        <el-table-column prop="code" label="部门编号"></el-table-column>

        <el-table-column label="操作" align="center" width="180" fixed="right" v-if="user.role=='ADMIN'">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="部门信息" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="父级" prop="pid">
<!--          <el-select v-model="form.pid" style="width: 100%" clearable>-->
<!--            <el-option v-for="item in parent" :key="item.id" :label="item.name" :value="item.id"></el-option>-->
<!--          </el-select>-->
          <el-select ref="selectTree" v-model="form.pid" :filterable="false" clearable style="width: 100%;">
            <el-option
                v-for="item in departmentTree"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                style="display: none;"/>
            <el-tree
                :data="departmentTree"
                :props="{children: 'children', label: 'name'}"
                highlight-current
                @node-click="handleNodeClick"
                default-expand-all/>
          </el-select>
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-input v-model="form.level" placeholder="层级"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="code">
          <el-input v-model="form.code" placeholder="部门编号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { saveAs } from 'file-saver';
export default {
  name: "Department",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      name: null,
      code: null,
      isSyncing: false,// 控制同步按钮的加载状态，默认为 false
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        level: [
          // {required: true, message: '请输入层级', trigger: 'blur'}
        ]
      },
      ids: [],
      parent: [],
      departmentList: [],
      departmentTree: [],
    }
  },
  created() {
    this.load(1)
    this.loadParent()
  },
  methods: {
    loadParent() {
      this.$request.get('/department/selectAll').then(res => {
        this.parent = res.data
      })
    },
    async syncDepartments() {
      this.$confirm('此操作将从泛微OA同步部门信息，覆盖现有数据并新增不存在的部门，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.isSyncing = true;
        try {
          const res = await this.$request.get('/department/sync-from-oa');

          if (res.code === '200') {
            this.$message.success('部门信息同步成功！');
            this.load();
          } else {
            this.$message.error(res.msg);
          }
        } catch (err) {
          this.$message.error(' 同步失败，请检查网络或后端服务 ');
          console.error('同步请求出错:', err);
        } finally {
          this.isSyncing = false;
        }
      }).catch(() => {
        this.$message.info('已取消同步');
      });
    },

    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.fromVisible = true   // 打开弹窗
    },
    handleEdit(row) {   // 编辑数据
      // 先查出扁平的部门数组
      this.$request.get('/department/selectAll').then(res => {
        this.departmentList = res.data
      })
      // 再查出树形的部门数组
      this.$request.get('/department/selectTree').then(res => {
        this.departmentTree = res.data
      })
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      if (this.form.pid === 0) {
        this.form.pid = '无父级部门'
      }
      this.fromVisible = true   // 打开弹窗
    },
    handleNodeClick(node) {
      this.$set(this.form, 'pid', node.id)
      this.$refs.selectTree.blur()
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/department/update' : '/department/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/department/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/department/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/department/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          code: this.code
        }
      }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data?.list || []
          this.total = res.data?.total || 0
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    reset() {
      this.name = null
      this.code = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load(this.pageNum)
    },
    exportData () {
      function extractFileName(disposition) {
        if (!disposition) return fallbackFileName();   // 关键兜底

        // 1. 先尝试 filename*=UTF-8''xxx
        const utf8Name = /filename\*=UTF-8''(.+)/i.exec(disposition);
        if (utf8Name) return decodeURIComponent(utf8Name[1]);

        // 2. 再尝试普通 filename="xxx" 或 filename=xxx
        const name = /filename=(?:''|")?([^;]+)(?:''|")?/i.exec(disposition);
        if (name) return decodeURIComponent(name[1].trim());

        return fallbackFileName();                     // 解析失败也兜底
      }
      /* 统一兜底：员工信息_yyyy-MM-dd_HHmm.xlsx */
      function fallbackFileName() {
        const now = new Date();
        const pad = n => String(n).padStart(2, '0');
        const dateStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
        const timeStr = `${pad(now.getHours())}${pad(now.getMinutes())}`;
        return `部门信息${dateStr}_${timeStr}.xlsx`;
      }
      this.$request.post('/department/export',{} ,{
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res.data],{
          type: res.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const disposition = res.headers['content-disposition'];
        const fileName = extractFileName(disposition);
        saveAs(blob, fileName);
        this.$message.success('导出成功')
      })
    }
  }
}
</script>

<style scoped>

</style>